import { DictType } from "../core/enum";
import { Http } from "../utils/http";
class Dict{
    static STORAGE_KEY='dict'
    _dictData = null

    constructor() {
        if (typeof Dict.instance==='object') {
            return Dict.instance
        }
        Dict.instance = this
        return this
    }
  
    getAllDictFromLocal() {
        return this._getDictData()
    }
    

    static async getServerDict(type) {
      return await Http.request({
        url: `xzl/housesInfo/dict?type=${type}`
      })
    }
  
    async getAllDictFromServer() {
      const dictData = this._getDictData()
      if (dictData) {
          return null
      }
      const promisArr = []
      const dictArr=Object.values(DictType)
      const obj = {}
      dictArr.forEach(item => {
        promisArr.push(
          new Promise((resolve, reject) => {
            Dict.getServerDict(item)
              .then(res => {
                resolve(res)
              })
              .catch(err => {
                reject(err)
              })
          })
        )
      })
      let data = await Promise.all(promisArr)
    
      data = data.filter((s) => {
        return s
      })
      data.forEach((item, index) => {
        obj[dictArr[index]] = []
        item.forEach(it => {
          // if (it) {
          const data = {
            name: it.name,
            value: it.value
          }
          obj[dictArr[index]].push(data)
          // }
        })
      })
      this._refreshByServerData(obj)
      this._refreshStorage()
      return this._getDictData()
    }

    _refreshByServerData(serverData) {
      this._dictData=serverData
    }


    isEmpty() {
        const dictData = this._getDictData()
        return !!dictData;
    }

    _refreshStorage() {
        wx.setStorageSync(Dict.STORAGE_KEY,this._dictData)
    }

    _getDictData() {
        if (this._dictData!==null) {
            return this._dictData
        }
        let dictData = wx.getStorageSync(Dict.STORAGE_KEY)
        if (!dictData) {
          dictData=null
        }
        this._dictData = dictData
        return dictData
    }
}
export{
  Dict
}